import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import Skeleton from 'taro-skeleton'
import {connect} from 'react-redux'
import {View, Image, Block} from '@tarojs/components'
import LocalGoodsBox from '../components/local-life-goods/big-goods-box'
import {
  CityLocation as CityLocationType,
  Good
} from '../../../utils/server.interface'
import {platform} from '../../../utils/platform-settting.service'
import {http} from '../../../utils/http'
import {
  QUERY_PRODUCT_LIST,
  ALI_GET_LOCATION_LIST,
  IDENTITY,
  RESOURCE_URL,
} from '../../../constants/api'
import CityLocation from '../components/city-location/city-location'
import {vcmonitor} from '../../../utils/tools'
import {user} from '../../../utils/user.service'
import SupportBar from '../../../components/support-bar/support-bar'
import {newHttp} from "../../../utils/request";
import {h5Wx} from "../../../utils/h5.service";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import './index.scss'

type PageStateProps = {
  location: CityLocationType
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  goods: Good[]
  showLoading: boolean
  pageshowLoading: boolean
  userIdentity: any
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps
}

@connect(({location}) => ({
  location
}), () => ({}))

class Index extends Component {
  state:
    { aliLocation: {}; goods: any[]; pageshowLoading: boolean; loadMoreStatus: string;userIdentity: any[]; showLoading: boolean; isLogin: any } = {
    loadMoreStatus: 'noMore',
    goods: [],
    showLoading: true,
    pageshowLoading: true,
    userIdentity: [],
    aliLocation: {},
    isLogin: '',
  }
  page = 1
  shareParams = ''

  async UNSAFE_componentWillMount() {
    if(await user.checkLogin()) {
      this.setState({userIdentity: await http.get(IDENTITY, {})})
    }
    this.setState({
      pageshowLoading: false,
      showLoading: false,
    })
    this.shareParams = await user.getSellerParams()
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
      const shareData = {
        title: platform.info.platformName,
        desc: '阿里本地生活',
        link: window.location.origin + '/other/aliLocalLife/local-life/index?' + this.shareParams,
        imgUrl: platform.info.platformLogo
      }
      await h5Wx.share(shareData)
    }
    this.page = 1
    const goods = await this.getGoods(this.page)
    let aliLocation = Taro.getStorageSync('aliCity')
    if (!Taro.getStorageSync('aliCity')) {
      if (Taro.getStorageSync('city')) {
        const searchCity = await newHttp.catchGet(ALI_GET_LOCATION_LIST, {cityName: Taro.getStorageSync('city').area_name.replace('市', '')})
        if (searchCity && searchCity.length > 0) {
          aliLocation = { area_name:searchCity[0].filterName,region_id:searchCity[0].filterKey }
          Taro.setStorageSync('aliCity', aliLocation)
        }
      } else {
        aliLocation = { area_name:'北京',region_id:'110100' }
      }
    }
    this.setState({
      goods,
      aliLocation
    })
  }

  async componentDidShow() {
    vcmonitor(this)
    const pages = Taro.getCurrentPages();
    const prevPage = pages[pages.length - 1]
    if (pages.length > 0 && prevPage.data.region_id) {
      const goods = await this.getGoods(1)
      const aliLocation = { area_name:prevPage.data.area_name,region_id:prevPage.data.region_id }
      delete prevPage.data.area_name
      delete prevPage.data.region_id
      this.setState({
        goods,
        aliLocation
      })
    }
    const isLogin = await user.checkLogin();
    if(isLogin) {
      this.setState({ isLogin })
    }
  }

  async getGoods(page = 1) {
    Taro.showLoading({ title: '加载中...' });
    let cityId = ''
    if (Taro.getStorageSync('aliCity')) {
      cityId = Taro.getStorageSync('aliCity').region_id
    } else if (Taro.getStorageSync('city')) {
      const searchCity = await newHttp.catchGet(ALI_GET_LOCATION_LIST, {cityName: Taro.getStorageSync('city').area_name.replace('市', '')})
      if (searchCity && searchCity.length > 0) {
        cityId = searchCity[0].filterKey
      }
    } else if (this.props.location.area_name != '全国') {
      const searchCity = await newHttp.catchGet(ALI_GET_LOCATION_LIST, { cityName: this.props.location.area_name.replace('市', '') });
      if (searchCity && searchCity.length > 0) {
        cityId = searchCity[0].filterKey;
      }
    } else {
      cityId = '110100'
    }
    const goodsData = await newHttp.catchGet(QUERY_PRODUCT_LIST, {
      cityId: cityId,
      pageIndex: page,
      pageSize: 10
    })
    if (goodsData.data) {
      if (goodsData.data.length < 10) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      Taro.hideLoading();
      return goodsData.data
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      Taro.hideLoading();
      return []
    }
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.goods
      this.page++
      const newData = await this.getGoods(this.page)
      this.setState({goods: [...old, ...newData]})
    }
  }

  onChange(value) {

  }

  async callbackonActionClick() {
    this.setState({goods: []}, async () => {
      const newData = await this.getGoods(this.page)
      this.setState({goods: newData})
    })
  }

  render() {
    const {aliLocation, userIdentity, goods, showLoading, pageshowLoading, isLogin} = this.state
    return (
      <View className='scenic-root' id='root'>
        <GzhAuth />
        <Skeleton title className='paddingNone' loading={showLoading} titleWidth='100%' rowHeight='75px'>
          <Block>
            <View className='local-life-head'>
              <View className='search-bar'>
                <CityLocation locations={aliLocation} type='lianlian' local='true'
                  onCallBackActionClick={this.callbackonActionClick.bind(this)}
                  onCallBackParent={this.onChange.bind(this)}
                />
              </View>
            </View>
          </Block>
        </Skeleton>
        <View className='zoom'>
          <Skeleton title loading={pageshowLoading} row={3} rowHeight={220}>
            <Block>
              <View className='bottom-goods'>
                <View className='local-list'>
                  <View className='top-name'>精选推荐</View>
                  <View>
                    <View />
                  </View>
                </View>
                {goods && goods.length > 0 && <LocalGoodsBox isSeller={userIdentity.isSeller} data={goods} isLogin={isLogin} />}
                {goods && goods.length == 0 &&
                <View className='listNull'>
                  <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' />
                  <View className='text'>什么都没有,去看看别的吧~</View>
                </View>
                }
              </View>
            </Block>
          </Skeleton>
        </View>
        <SupportBar />
      </View>
    )
  }
}

export default Index as unknown as ComponentClass<PageOwnProps, PageState>
